package com.abel.quiz.controller;/**
 * Created by abel.lin on 2017/8/4.
 */

import com.abel.quiz.po.UserInfoPo;
import com.abel.quiz.services.UserInfoService;
import com.abel.quiz.socket.Message;
import com.abel.quiz.socket.SystemWebSocketHandler;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author abel.lin
 * @date_time 2017/8/4 13:11
 * @description
 */
@RequestMapping("front")
@Controller
public class IndexController extends BaseController{
    @Resource
    SystemWebSocketHandler handler;
    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response){
        return new ModelAndView("front/login");
    }
    @RequestMapping("doLogin")
    public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        request.getSession().setAttribute("uid", id);
        request.getSession().setAttribute("name","1".equals(id)?"张三":"李四");
        return new ModelAndView("redirect:/front/index");
    }

    @RequestMapping("index")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView("front/index");
        return view;
    }

    @RequestMapping("msg")
    public ModelAndView msg(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view = new ModelAndView("front/msg");
        return view;
    }

    @ResponseBody
    @RequestMapping("broadcast")
    public void broadcast(HttpServletRequest request, HttpServletResponse response,
                                  String text) throws IOException {
        Message msg = new Message();
        msg.setDate(new Date());
        msg.setFrom(-1L);
        msg.setFromName("系统广播");
        msg.setTo(0L);
        msg.setText(text);
        handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
    }

}
